package com.hmy.uaa.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hmy.uaa.common.properties.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OssStsUtil {
    @Autowired
    private OssProperties ossProperties;


    /**
     * 获取临时授权访问
     * <p>
     * endpoint：STS接入地址，例如sts.cn-hangzhou.aliyuncs.com。各地域的STS接入地址请参见接入地址。
     * AccessKeyId、AccessKeySecret：访问密钥。
     * RoleArn：角色ARN。
     * RoleSessionName：用来标识临时访问凭证的名称，建议使用不同的应用程序用户来区分。
     * Policy：在扮演角色的时候额外添加的权限限制。请参见如何构建RAM Policy。 @See https://help.aliyun.com/document_detail/100680.html?spm=a2c4g.11186623.2.22.13e852a9QuGA3Z#concept-y5r-5rm-2gb
     */
    public AssumeRoleResponse.Credentials getCredentials() throws ClientException {
        String stsEndpoint = ossProperties.getStsEndpoint();
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        String roleArn = ossProperties.getRoleArn();
        try {
            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
            DefaultProfile.addEndpoint("", "", "Sts", stsEndpoint);

            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName("session-name");
            request.setPolicy(null);
            request.setDurationSeconds(3600L);
            final AssumeRoleResponse response = client.getAcsResponse(request);
            AssumeRoleResponse.Credentials credentials = response.getCredentials();

            log.info("credentials:{}", credentials.getSecurityToken());
            return credentials;
        } catch (ClientException e) {
            log.info("文件上传出错,异常为:", e);
            throw e;
        }
    }

//    public AssumeRoleResponse.Credentials getCachedCredentials() throws ClientException, IOException {
//        if (Objects.nonNull(redisTemplate.opsForValue().get(Constant.OSS_STS_CREDENTIALS))) {
//            return objectMapper.readValue(redisTemplate.opsForValue().get(Constant.OSS_STS_CREDENTIALS), AssumeRoleResponse.Credentials.class);
//        }
//        AssumeRoleResponse.Credentials credentials = getCredentials();
//        redisTemplate.opsForValue().set(Constant.OSS_STS_CREDENTIALS, objectMapper.writeValueAsString(credentials), Duration.ofSeconds(3550L));
//        return credentials;
//    }
//
//    public OSS getOssClient() {
//        AssumeRoleResponse.Credentials credentials;
//        try {
//            credentials = this.getCachedCredentials();
//        } catch (ClientException | IOException e) {
//            log.error("获取临时授权访问失败：", e);
//            throw new ClientException("获取临时授权访问失败");
//        }
//        return new OSSClientBuilder().build(ossProperties.getEndpoint(), credentials.getAccessKeyId(),
//                credentials.getAccessKeySecret(), credentials.getSecurityToken());
//    }
}
